<template>
  <div class="history-query-box">
    <!-- 下拉列表 -->
    <el-card class="content__left">
      <realtimemonito-menu :data="menus" v-model:menu-id="menuId" v-model:open-id="openId" @menu-click="commEvent.menuClick" />
    </el-card>
    <!-- 展示信息 -->
    <div class="content__right">
      <el-card>
        <div class="container__header">历史数据</div>
        <!-- 导出按钮 -->
        <el-row justify="end">
          <el-button type="success" icon="Download" @click="showExportDialog = true">导出数据</el-button>
        </el-row>
        <el-row :gutter="20" class="container__search">
          <el-col :span="4">
            <el-segmented v-model="dateRange" :options="dateOption" @change="commEvent.onDateRange" />
          </el-col>
          <el-col :span="5">
            <div class="container__form">
              <div class="form__label">时间：</div>
              <div class="form__value">
                <el-date-picker
                  v-model="searchValue.dataTime"
                  :type="dataTimeType"
                  placeholder="请选择"
                  style="width: 100%"
                  :clearable="false"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="5">
            <div class="container__form">
              <div class="form__label">能源类型：</div>
              <div class="form__value">
                <el-select
                  v-model="searchValue.energyType"
                  placeholder="请选择能源类型"
                  style="width: 100%"
                  filterable
                  @change="commEvent.getDeviceOption"
                >
                  <el-option v-for="item in energyTypeEnum" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :span="5">
            <div class="container__form">
              <div class="form__label">生产设备：</div>
              <div class="form__value">
                <el-select v-model="searchValue.deviceId" placeholder="请选择生产设备" filterable>
                  <el-option v-for="item in deviceOption" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :span="5">
            <el-row justify="end">
              <el-button icon="Search" type="primary" @click="commEvent.getTableData">搜索</el-button>
              <el-button icon="Refresh" @click="commEvent.onReset">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
        <!-- 图表信息 -->
        <div v-if="tabelData.length" class="chart-box">
          <e-charts :option="tableOption" />
        </div>
        <el-empty v-else />
      </el-card>
    </div>

    <!-- 导出对话框 -->
    <export-dialog v-model="showExportDialog" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue"
import { useRoute } from "vue-router"
import ECharts from "@/components/ECharts/index.vue"
import RealtimemonitoMenu, { MenuType } from "../components/RealtimemonitoMenu.vue"
import ExportDialog from "./components/ExportDialog.vue"
import { dateOption, dateValue, tableChart } from "./enum"
import { energyTypeEnum } from "@/utils/enum"
import dayjs from "dayjs"
import { historyStat } from "@/api/modules/energy"
import { SystemSpace } from "@/api/interface/energy"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { deviceListEnergy } from "@/api/modules/archive"
import { SystemSpace as SystemArchive } from "@/api/interface/archive"
import { ECOption } from "@/components/ECharts/config"

const route = useRoute()

// 参数
const tabelData = ref<SystemSpace.HistoryStat[]>([]) // 表格数据
const dateRange = ref<string>("hour")
const menus = ref<MenuType[]>([]) // 菜单树结构
const openId = ref<number[]>([]) // 展开id
const menuId = ref<number>(-1) //菜单选中id
const energyUnit = ref<string>("kWh") // 能源单位
const showExportDialog = ref<boolean>(false) // 显示导出对话框
// 搜素信息
const searchValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number,
  deviceId: 0,
  dataTime: dayjs().format("YYYY-MM-DD"),
  energyType: "electric"
})
const dataTimeType = computed<"date" | "month" | "year">(() => {
  const _enum: any = {
    hour: "date",
    day: "month",
    month: "year"
  }
  return _enum[dateRange.value]
})
const deviceOption = ref<SystemArchive.DeviceListEnergy[]>([]) // 设备列表

// 图表数据
const tableOption = computed<ECOption>(() => {
  let _series: any = {}
  if (tableChart?.series && Array.isArray(tableChart.series)) {
    _series = tableChart.series[0]
  }
  return {
    ...tableChart,
    xAxis: { ...tableChart.xAxis, data: tabelData.value.map(item => item.dataTime) },
    yAxis: { ...tableChart.yAxis, name: energyUnit.value },
    series: [{ ..._series, data: tabelData.value.map(item => item.value) }]
  }
})
// 事件
const commEvent = {
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await organTree()
    menus.value = commEvent.formatMenu(data)
    if (data && data.length > 0) {
      const _id: number = data[0].id
      menuId.value = _id
      openId.value = [_id]
    }
    commEvent.getTableData()
  },
  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.pid,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },
  // 获取设备信息
  getDeviceOption: async () => {
    const params: SystemArchive.DeviceListEnergyQuery = {
      factoryId: searchValue.value.factoryId,
      lineId: searchValue.value.lineId,
      energyType: searchValue.value.energyType
    }
    const { data } = await deviceListEnergy(params)
    deviceOption.value = [{ name: "全部", id: 0, code: "" }, ...data]
    searchValue.value.deviceId = 0
  },
  // 修改日期区间
  onDateRange: (value: string) => {
    const _date: any = {
      hour: dayjs().format("YYYY-MM-DD"),
      day: dayjs().format("YYYY-MM"),
      month: dayjs().format("YYYY")
    }
    searchValue.value.dataTime = _date[value]
    commEvent.getTableData()
  },
  // 菜单点击
  menuClick: (item: any) => {
    if (item.level === 1) {
      searchValue.value.factoryId = item.id
      searchValue.value.lineId = undefined
    } else if (item.level === 2) {
      searchValue.value.factoryId = item.pid
      searchValue.value.lineId = item.id
    } else {
      searchValue.value.factoryId = undefined
      searchValue.value.lineId = undefined
    }
    commEvent.getDeviceOption()
    commEvent.getTableData()
  },
  // 重置功能
  onReset: () => {
    // 重置日期范围
    dateRange.value = "hour"

    // 重置搜索条件为初始值
    searchValue.value = {
      factoryId: undefined,
      lineId: undefined,
      deviceId: 0,
      dataTime: dayjs().format("YYYY-MM-DD"),
      energyType: "electric"
    }

    // 清空表格数据
    tabelData.value = []

    // 重置菜单选择为第一个
    if (menus.value.length > 0) {
      const firstMenu = menus.value[0]
      menuId.value = firstMenu.id
      openId.value = [firstMenu.id]

      // 根据第一个菜单项设置厂区和产线信息
      if (firstMenu.level === 1) {
        searchValue.value.factoryId = firstMenu.id
        searchValue.value.lineId = undefined
      }
    }

    // 重置能源单位
    energyUnit.value = "kWh"

    // 重新获取设备选项和表格数据
    commEvent.getDeviceOption().then(() => {
      commEvent.getTableData()
    })
  },
  // 查询表格/图表数据
  getTableData: async () => {
    const _date: any = {
      hour: { time: dayjs(searchValue.value.dataTime).format("YYYYMMDD"), suffix: "时" },
      day: { time: dayjs(searchValue.value.dataTime).format("YYYYMM"), suffix: "日" },
      month: { time: dayjs(searchValue.value.dataTime).format("YYYY"), suffix: "月" }
    }
    const _dataTime: string = _date[dateRange.value].time
    const _suffix: string = _date[dateRange.value].suffix
    const _timeType: number = dateValue[dateRange.value].timeType
    const params: SystemSpace.HistoryStatQuery = {
      ...searchValue.value,
      deviceId: searchValue.value.deviceId === 0 ? undefined : searchValue.value.deviceId,
      dataTime: _dataTime,
      timeType: _timeType
    }
    const { data } = await historyStat(params)
    tabelData.value = data.map(item => ({
      ...item,
      value: item.value || 0,
      dataTime: item.dataTime.substring(item.dataTime.length - 2) + _suffix
    }))
    if (searchValue.value.energyType === "electric") {
      energyUnit.value = "kWh"
    } else {
      energyUnit.value = "m³"
    }
  }
}
// 监听路由参数变化
watch(
  () => route.query,
  newQuery => {
    if (newQuery.dataTime && newQuery.energyType && newQuery.timeType) {
      // 设置查询参数
      searchValue.value.energyType = String(newQuery.energyType)

      // 根据timeType设置日期范围
      const timeType = Number(newQuery.timeType)
      if (timeType === 4) {
        dateRange.value = "hour"
      } else if (timeType === 3) {
        dateRange.value = "day"
      } else if (timeType === 2) {
        dateRange.value = "month"
      }

      // 格式化日期时间
      const dataTimeStr = String(newQuery.dataTime)
      if (dataTimeStr.length === 8) {
        // YYYYMMDD格式
        const year = dataTimeStr.substring(0, 4)
        const month = dataTimeStr.substring(4, 6)
        const day = dataTimeStr.substring(6, 8)
        searchValue.value.dataTime = `${year}-${month}-${day}`
      }

      console.log("从消息页面接收到参数：", newQuery)
      console.log("设置查询条件：", searchValue.value)

      // 延迟执行查询，确保组件已初始化
      setTimeout(() => {
        commEvent.getTableData()
      }, 500)
    }
  },
  { immediate: true }
)

onMounted(() => {
  commEvent.getMenus()
  commEvent.getDeviceOption()
})
</script>

<style lang="scss" scoped>
.mt-10 {
  margin-top: 10px;
}
.mb-10 {
  margin-bottom: 10px;
}
.my-10 {
  margin: 10px 0;
}
.w-full {
  width: 100%;
}
.history-query-box {
  display: flex;
  width: 100%;
  height: calc(100vh - 100px);
  .content__left {
    width: 200px;
    :deep(.el-card__body) {
      padding: 0;
    }
    height: 100%;
    overflow-y: auto;
    padding-right: 4px; /* 为滚动条留空间 */
    scroll-behavior: smooth;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 3px;
    }
  }
  .content__right {
    box-sizing: border-box;
    flex: 1;
    min-width: 0;
    padding: 0 10px;
    overflow-y: auto;
    .container__header {
      position: relative;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      width: 100%;
      padding-left: 8px;
      font-size: 16px;
      font-weight: bold;
      &::before {
        position: absolute;
        left: 0;
        width: 3px;
        height: 75%;
        content: "";
        background-color: #1d4a9d;
        border-radius: 16px;
      }
    }
    .container__search {
      margin: 20px 0;
      .container__form {
        display: flex;
        align-items: center;
        width: 100%;
        .form__label {
          flex-shrink: 0;
          font-size: 13px;
        }
        .form__value {
          flex: 1;
        }
      }
    }
    .chart-box {
      width: 100%;
      height: 450px;
    }
    .table-box {
      width: 100%;
    }
  }
}
</style>
